<template>
    <div class="system-settings">
        <!-- 顶部标题 -->
        <div class="header">
            <i class="el-icon-setting" style="font-size: 24px; margin-right: 8px; vertical-align: middle;"></i>
            <span style="font-size: 24px; font-weight: bold; color: #333; vertical-align: middle;">系统设置</span>
        </div>

        <!-- 标签页 -->
        <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
            <el-tab-pane label="基础设置" name="base"></el-tab-pane>
            <el-tab-pane label="库存设置" name="inventory"></el-tab-pane>
            <el-tab-pane label="通知设置" name="notification"></el-tab-pane>
            <el-tab-pane label="安全设置" name="security"></el-tab-pane>
        </el-tabs>

        <!-- 内容区域 -->
        <div class="content-wrapper">
            <!-- 基础设置 -->
            <div v-if="activeTab === 'base'" class="setting-section">
                <el-form :model="baseForm" label-width="120px" >
                    <el-form-item label="系统名称" style="width: 500px;">
                        <el-input v-model="baseForm.sys_name" placeholder="请输入系统名称" />
                    </el-form-item>
                    <el-form-item label="系统版本" style="width: 500px;">
                        <el-input v-model="baseForm.sys_version" disabled />
                    </el-form-item>
                    <el-form-item label="系统描述">
                        <el-input v-model="baseForm.sys_desc" type="textarea" :rows="4" placeholder="请输入系统描述" />
                    </el-form-item>
                    <el-form-item label="默认仓库" style="width: 500px;">
                        <el-checkbox v-model="baseForm.default_house" :true-value="1" :false-value="0" />
                    </el-form-item>
                    <el-form-item label="数据保留天数">
                        <el-input-number v-model="baseForm.data_retention_days" :min="1" />
                    </el-form-item>
                    <el-form-item label="系统通知邮箱" style="width: 500px;">
                        <el-input v-model="baseForm.system_notic_email" placeholder="请输入通知邮箱" />
                    </el-form-item>
                    <el-form-item label="启用库存预警">
                        <el-checkbox v-model="baseForm.enable_inventory_alerts" />
                    </el-form-item>
                    <el-form-item label="启用功能" style="margin-bottom: 10px;">
                        <div style="display: flex; gap: 20px; align-items: center;">
                            <el-checkbox v-model="baseForm.enable_generation_plan">采购计划自动生成</el-checkbox>
                            <el-checkbox v-model="baseForm.enable_analysis_reports">经营数据分析报告自动发送</el-checkbox>
                        </div>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 库存设置 -->
            <div v-else-if="activeTab === 'inventory'" class="setting-section">
                <el-form :model="inventoryForm" label-width="120px" >
                    <el-form-item label="最低库存阈值">
                        <el-input v-model="inventoryForm.stock_alert_min" placeholder="请输入最低库存数量" />
                    </el-form-item>
                    <el-form-item label="最高库存阈值">
                        <el-input v-model="inventoryForm.stock_alert_max" placeholder="请输入最高库存数量" />
                    </el-form-item>
                </el-form>
            </div>

            <!-- 通知设置 -->
            <div v-else-if="activeTab === 'notification'" class="setting-section">
                <el-form :model="notificationForm" label-width="120px">
                    <el-form-item label="通知方式">
                        <el-radio-group v-model="notificationForm.notification_method">
                            <el-radio label="邮件通知" />
                            <el-radio label="系统内通知" />
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="通知偏好">
                        <el-checkbox-group v-model="notificationForm.notification_preferences">
                            <el-checkbox label="采购计划通知">自动生成采购计划时发送通知</el-checkbox>
                            <el-checkbox label="经营日报通知">每日经营数据报告</el-checkbox>
                            <el-checkbox label="系统维护通知">系统更新和维护通知</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                    <el-form-item label="通知时间设置">
                        <el-form-item label="日报发送时间">
                            <el-time-picker v-model="notificationForm.daily_report_time" placeholder="选择时间"
                                format="YYYY-MM-DD HH:mm" value-format="HH:mm" />
                        </el-form-item>
                        <el-form-item label="周报发送时间">
                            <el-select v-model="notificationForm.week_report_time" placeholder="请选择周报发送日"
                                style="width: 150px;">
                                <el-option label="周日" value="Sunday" />
                                <el-option label="周一" value="Monday" />
                                <el-option label="周二" value="Tuesday" />
                                <el-option label="周三" value="Wednesday" />
                                <el-option label="周四" value="Thursday" />
                                <el-option label="周五" value="Friday" />
                                <el-option label="周六" value="Saturday" />
                            </el-select>
                        </el-form-item>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 安全设置 -->
            <div v-else-if="activeTab === 'security'" class="setting-section">
                <el-form :model="securityForm" label-width="120px" >
                    <el-form-item label="密码最小长度">
                        <el-input-number v-model="securityForm.pwd_length" :min="1" />
                    </el-form-item>
                    <el-form-item label="包含数字" >
                        <el-checkbox v-model="securityForm.passwordRequireNumber" />
                    </el-form-item>
                    <el-form-item label="包含大小写字母" style="width: 200px;">
                        <el-checkbox v-model="securityForm.passwordRequireAlpha" />
                    </el-form-item>
                    <el-form-item label="包含特殊字符">
                        <el-checkbox v-model="securityForm.passwordRequireSpecial" />
                    </el-form-item>
                    <el-form-item label="登录失败次数">
                        <el-input-number v-model="securityForm.maxLoginFailCount" :min="1" />
                    </el-form-item>
                    <el-form-item label="会话超时时间">
                        <el-input-number v-model="securityForm.sessionTimeoutMinutes" :min="1" />
                    </el-form-item>

                    <el-form-item label="操作日志">
                        <el-checkbox v-model="securityForm.logUserOperations" /> &nbsp;记录用户操作日志
                    </el-form-item>
                    <el-form-item label="系统错误日志">
                        <el-checkbox v-model="securityForm.logSystemErrors" />
                    </el-form-item>
                    <el-form-item label="更新时间">
                        <el-date-picker v-model="securityForm.updateTime" type="datetime" placeholder="选择更新时间"
                            value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" style="width: 200px;" />
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <!-- 底部按钮 -->
        <div class="footer-actions">

            <el-button type="primary" @click="saveSettings">保存设置</el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getSettings, updateSettings } from '../../api/settings'

// 标签页状态
const activeTab = ref('base')

// 表单数据
const baseForm = reactive({
    sys_name: '',
    sys_version: '',
    sys_desc: '',
    default_house: '',
    data_retention_days: null,
    system_notic_email: '',
    enable_inventory_alerts: false,
    enable_generation_plan: false,
    enable_analysis_reports: false
})

const inventoryForm = reactive({
    stock_alert_min: '',
    stock_alert_max: ''
})

const notificationForm = reactive({
    notification_method: '',
    notification_preferences: [],
    daily_report_time: '',
    weekly_report_day: '',
    week_report_time: 'Sunday'
})

const securityForm = reactive({
    pwd_length: null,
    passwordRequireNumber: false,
    passwordRequireAlpha: false,
    passwordRequireSpecial: false,
    enableLoginFailLimit: false,
    maxLoginFailCount: null,
    enableSessionTimeout: false,
    sessionTimeoutMinutes: null,
    logUserOperations: false,
    logSystemErrors: false,
    updateTime: ''
})

// 获取设置数据
const fetchSettings = async () => {
    try {
        const res = await getSettings()
        if (res.code === 0) {
            const data = res.data || {}

            // 基础设置
            baseForm.sys_name = data.sys_name || baseForm.sys_name
            baseForm.sys_version = data.sys_version || baseForm.sys_version
            baseForm.sys_desc = data.sys_desc || baseForm.sys_desc
            // 处理默认仓库，1为启用(true)，0为禁用(false)
            baseForm.default_house = (data.default_house === 1 ||
                data.default_house === '1' ||
                data.default_house === true) ? 1 : 0
            baseForm.data_retention_days = data.data_retention_days || baseForm.data_retention_days
            baseForm.system_notic_email = data.system_notic_email || baseForm.system_notic_email

            // 处理启用自动库存预警，1为启用(true)，0为禁用(false)
            baseForm.enable_inventory_alerts = (data.enable_inventory_alerts === 1 ||
                data.enable_inventory_alerts === '1' ||
                data.enable_inventory_alerts === true) ? true : false

            baseForm.enable_generation_plan = (data.enable_generation_plan === 1 ||
                data.enable_generation_plan === '1' ||
                data.enable_generation_plan === true) ? true : false
            baseForm.enable_analysis_reports = (data.enable_analysis_reports === 1 ||
                data.enable_analysis_reports === '1' ||
                data.enable_analysis_reports === true) ? true : false

            // 库存设置
            inventoryForm.stock_alert_min = data.stock_alert_min || inventoryForm.stock_alert_min
            inventoryForm.stock_alert_max = data.stock_alert_max || inventoryForm.stock_alert_max

            // 通知设置 - 处理通知方式：0是邮件通知,1是系统内通知
            if (data.notification_method !== undefined) {
                // 根据数据库值设置单选按钮选项
                if (data.notification_method === 0 || data.notification_method === '0') {
                    notificationForm.notification_method = '邮件通知'
                } else if (data.notification_method === 1 || data.notification_method === '1') {
                    notificationForm.notification_method = '系统内通知'
                } else if (data.notification_method === 2 || data.notification_method === '2') {
                    notificationForm.notification_method = 'both'
                } else {
                    notificationForm.notification_method = '邮件通知' // 默认值
                }
            } else {
                notificationForm.notification_method = '邮件通知' // 默认值
            }

            // 通知设置 - 处理通知偏好
            notificationForm.notification_preferences = []
            if (data.notification_preferences && typeof data.notification_preferences === 'string') {
                const prefs = data.notification_preferences.split(',').map(p => p.trim())
                notificationForm.notification_preferences = prefs
            }

            // 处理日报发送时间：提取 HH:mm
            if (data.daily_report_time) {
                const date = new Date(data.daily_report_time)
                const hours = date.getHours().toString().padStart(2, '0')
                const minutes = date.getMinutes().toString().padStart(2, '0')
                notificationForm.daily_report_time = `${hours}:${minutes}`
            }

            if (data.week_report_time) {
                const date = new Date(data.week_report_time)
                const dayName = date.toLocaleDateString('zh-CN', { weekday: 'long' })
                const weekMap = {
                    '星期日': 'Sunday',
                    '星期一': 'Monday',
                    '星期二': 'Tuesday',
                    '星期三': 'Wednesday',
                    '星期四': 'Thursday',
                    '星期五': 'Friday',
                    '星期六': 'Saturday'
                }
                notificationForm.week_report_time = weekMap[dayName] || 'Sunday'
            } else {
                notificationForm.week_report_time = 'Sunday'
            }

            // 安全设置
            securityForm.pwd_length = data.pwd_length || securityForm.pwd_length

            // 必须包含数字
            securityForm.passwordRequireNumber = (data.pwd_require_num === 1 ||
                data.pwd_require_num === '1' ||
                data.pwd_require_num === true) ? true : false

            // 必须包含大小写字母
            securityForm.passwordRequireAlpha = (data.pwd_require_word === 1 ||
                data.pwd_require_word === '1' ||
                data.pwd_require_word === true) ? true : false

            // 必须包含特殊字符
            securityForm.passwordRequireSpecial = (data.pwd_require_special === 1 ||
                data.pwd_require_special === '1' ||
                data.pwd_require_special === true) ? true : false

            // 登录失败次数限制
            securityForm.enableLoginFailLimit = (data.login_failur === 1 ||
                data.login_failur === '1' ||
                data.login_failur === true) ? true : false

            // 最大登录失败次数
            securityForm.maxLoginFailCount = data.login_failur || securityForm.maxLoginFailCount

            // 启用会话超时
            securityForm.enableSessionTimeout = (data.session_timeout > 0) ? true : false

            // 会话超时时间
            securityForm.sessionTimeoutMinutes = data.session_timeout || securityForm.sessionTimeoutMinutes

            // 记录用户操作日志
            securityForm.logUserOperations = (data.record_user_log === 1 ||
                data.record_user_log === '1' ||
                data.record_user_log === true) ? true : false

            // 记录系统错误日志
            securityForm.logSystemErrors = (data.record_sys_error === 1 ||
                data.record_sys_error === '1' ||
                data.record_sys_error === true) ? true : false

            // 更新时间
            if (data.update_time) {
                securityForm.updateTime = data.update_time // 假设后端返回的是 ISO 字符串或标准 datetime 字符串
            } else {
                securityForm.updateTime = new Date().toISOString().replace('T', ' ').slice(0, 19) // 默认当前时间
            }
        } else {
            ElMessage.error(res.msg || '获取系统设置失败')
        }
    } catch (error) {
        ElMessage.error('网络异常，请检查连接')
    }
}

// 标签页点击事件
const handleTabClick = (tab) => {
}

// 保存设置
const saveSettings = async () => {
    try {
        // 构建要发送的数据
        const formData = {
            // 基础设置
            sys_name: baseForm.sys_name,
            sys_version: baseForm.sys_version,
            sys_desc: baseForm.sys_desc,
            default_house: baseForm.default_house, // 直接使用值，不需要转换
            data_retention_days: baseForm.data_retention_days,
            system_notic_email: baseForm.system_notic_email,
            enable_inventory_alerts: baseForm.enable_inventory_alerts ? 1 : 0,
            enable_generation_plan: baseForm.enable_generation_plan ? 1 : 0,
            enable_analysis_reports: baseForm.enable_analysis_reports ? 1 : 0,

            // 库存设置
            stock_alert_min: inventoryForm.stock_alert_min,
            stock_alert_max: inventoryForm.stock_alert_max,

            // 通知设置
            notification_method: (() => {
                switch (notificationForm.notification_method) {
                    case '邮件通知': return 0;
                    case '系统内通知': return 1;
                    default: return 0;
                }
            })(),
            notification_preferences: notificationForm.notification_preferences.join(','),
            daily_report_time: notificationForm.daily_report_time, // 直接使用完整的时间字符串
            week_report_time: notificationForm.week_report_time,

            // 安全设置
            pwd_length: securityForm.pwd_length,
            pwd_require_num: securityForm.passwordRequireNumber ? 1 : 0,
            pwd_require_word: securityForm.passwordRequireAlpha ? 1 : 0,
            pwd_require_special: securityForm.passwordRequireSpecial ? 1 : 0,
            login_failur: securityForm.maxLoginFailCount,
            session_timeout: securityForm.sessionTimeoutMinutes,
            record_user_log: securityForm.logUserOperations ? 1 : 0,
            record_sys_error: securityForm.logSystemErrors ? 1 : 0,
            update_time: securityForm.updateTime
        }

        // 调用更新API
        const res = await updateSettings(formData)

        if (res.code === 0) {
            ElMessage.success('保存设置成功')
            // 重新获取最新设置
            fetchSettings()
        } else {
            ElMessage.error(res.msg || '保存设置失败')
        }
    } catch (error) {
        console.error('保存设置时发生错误:', error)
        ElMessage.error('网络异常，请检查连接')
    }
}

// 组件挂载时获取数据
onMounted(() => {
    fetchSettings()
})
</script>

<style scoped>
.system-settings {
    padding: 20px;
    background-color: white;
}

.header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 20px;
    font-size: 20px;
    font-weight: bold;
    color: #333;
}

.setting-section {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 20px;
    margin-bottom: 20px;
}

.footer-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
}

.el-tabs--card .el-tabs__item {
    padding: 0 12px;
    height: 32px;
    line-height: 32px;
    font-size: 14px;
    color: #606266;
}

.el-tabs--card .el-tabs__item.is-active {
    color: #1B82F1;
    border-bottom: 2px solid #1B82F1;
}

.el-form-item__label {
    font-weight: normal;
    color: #333;
}

.el-form-item__content {
    margin-left: 0;
}

.el-form-item__error {
    margin-top: 4px;
}
</style>